package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架
 * 每天晚上3点；上架最近三天需要秒杀的商品。
 */
@Slf4j
@Service
public class SeckillSkuScheduled {

    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    //上架锁
    private final String upload_lock = "seckill:upload:lock";

    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSkuLate3Days(){
        log.info("上架秒杀商品的信息.....");

        //保证幂等性 加入分布式锁 防止多个服务同时进入这里通知执行秒杀商品上架功能
        RLock upLock = redissonClient.getLock(upload_lock);
        upLock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuLate3Days();
        }finally {
            upLock.unlock();
        }

    }



}





















